package com.example.system_backend.service.impl;

import com.example.system_backend.entity.Teeth;
import com.example.system_backend.entity.TeethTreat;
import com.example.system_backend.entity.Treatment;
import com.example.system_backend.entity.User;
import com.example.system_backend.repository.TeethRepository;
import com.example.system_backend.repository.TeethTreatRepository;
import com.example.system_backend.repository.TreatmentRepository;
import com.example.system_backend.repository.UserRepository;
import com.example.system_backend.service.TreatmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TreatmentServiceImpl implements TreatmentService {

    @Autowired
    private TreatmentRepository treatmentRepository;
    @Autowired
    private TeethRepository teethRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private TeethTreatRepository teethTreatRepository;

    @Override
    public Integer creatTreatment(String name, String patientEmail, String dentistEmail) {
        User user = userRepository.findByEmail(patientEmail);
        if (user == null) {
            return 1;
        }
        if (user.getType() == 2) {
            return 1;
        }
        Treatment treatment = new Treatment();
        treatment.setName(name);
        treatment.setUserEmail(patientEmail);
        treatment.setDtEmail(dentistEmail);
        treatmentRepository.save(treatment);
        return 0;
    }

    @Override
    public List<Treatment> treatmentByDt(String dentistEmail) {
        List<Treatment> treatmentList = treatmentRepository.findAllByDtEmail(dentistEmail);
        return treatmentList;
    }

    @Override
    public List<Teeth> teethByTreat(Integer treatmentId) {
        List<Teeth> teethList = new ArrayList<>();
        List<TeethTreat> teethTreats = teethTreatRepository.findAllByTreatId(treatmentId);
        for (TeethTreat teethTreat: teethTreats) {
            Integer teethId = teethTreat.getTeethId();
            Teeth teeth = teethRepository.findById(teethId).get();
            teethList.add(teeth);
        }
        return teethList;
    }

    @Override
    public Integer add2Treatment(Integer teethId, Integer treatmentId) {
        TeethTreat teethTreat = teethTreatRepository.findByTeethIdAndTreatId(teethId, treatmentId);
        if (teethTreat != null) {
            return 1;
        }
        teethTreat = new TeethTreat();
        teethTreat.setTeethId(teethId);
        teethTreat.setTreatId(treatmentId);
        teethTreatRepository.save(teethTreat);
        return 0;
    }

    @Override
    public List<Treatment> treatmentByUser(String userEmail) {
        List<Treatment> treatmentList = treatmentRepository.findAllByUserEmail(userEmail);
        return treatmentList;
    }
}
